import {
  createProductAttribute,
  deleteProductAttribute,
  getProductAttributeList,
  updateProductAttribute,
} from '@/services/ant-design-pro/product';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FormControlRender,
  ModalForm,
  PageContainer,
  pickControlPropsWithId,
  ProDescriptions,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Card, Drawer, message, Popconfirm, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { FormValueType } from './components/UpdateForm';

import { Form, Input, Space } from 'antd';

const DynamicInput = ({ value, onChange }) => {
  const inputs = value || [];
  console.log('[value]', inputs);
  // const [inputs, setInputs] = useState<{ id?: string; value: string }[]>([]);

  // 添加新的输入框
  const addInput = () => {
    const newInput = { value: '' };
    // setInputs([...inputs, newInput]);

    onChange([...inputs, newInput]);
  };

  // 删除指定输入框
  const removeInput = (targetIndex: number) => {
    onChange(inputs.filter((input, index) => index !== targetIndex));

    // setInputs(inputs.filter((input, index) => index !== targetIndex));
  };

  // 更新输入框的值
  const handleInputChange = (targetIndex: number, value: string) => {
    onChange(inputs.map((input, index) => (targetIndex === index ? { ...input, value } : input)));
    // setInputs(inputs.map((input, index) => (targetIndex === index ? { ...input, value } : input)));
  };

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%' }}>
        {(inputs || []).map((input, index) => (
          <Card
            key={index}
            title={`第${index + 1}项`}
            extra={
              <Button
                danger
                type="primary"
                onClick={() => removeInput(index)}
                style={{ width: '100%' }}
              >
                删除
              </Button>
            }
          >
            <Form.Item
              // name={[index, 'value']}
              required
              style={{ marginBottom: 0 }}
              layout="vertical"
            >
              <Input
                value={input.value}
                onChange={(e) => handleInputChange(index, e.target.value)}
                placeholder="请输入内容"
              />
            </Form.Item>

            <Form.Item name={['attributeValues', index, 'id']} hidden>
              <Input />
            </Form.Item>
          </Card>
        ))}
      </Space>
      <Button type="primary" onClick={addInput} style={{ marginTop: 10 }}>
        添加
      </Button>
      {/* <pre style={{ marginTop: 20 }}>{JSON.stringify(inputs, null, 2)}</pre> */}
    </div>
  );
};

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
  const hide = message.loading('正在添加');
  try {
    const data = { status: 1, ...fields };
    // data.values = data.values.map((item) => {
    //   return {
    //     value: item,
    //   };
    // });
    data.values = data.attributeValues;

    const resp = await await createProductAttribute(data);
    hide();
    if (resp?.code === 1) {
      return;
    }
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败，请重试。');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('更新中');
  try {
    const data = { status: 1, ...fields };
    // data.values = data.values.map((item) => {
    //   return {
    //     value: item,
    //   };
    // });
    data.values = data.attributeValues;

    const resp = await updateProductAttribute(data);
    hide();
    if (resp?.code === 1) {
      return;
    }
    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败');
    return false;
  }
};

const TableList: React.FC = () => {
  const [dataSource, setDataSource] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      search: false,
      title: '名称',
      dataIndex: 'name',
    },
    {
      search: false,
      title: 'SKU项',
      dataIndex: 'attributeValues',
      render: (data) => {
        return data?.map((item) => (
          <Tag color="blue" key={item.id}>
            {item.value}
          </Tag>
        ));
      },
    },
    {
      search: false,
      title: '选择类型',
      dataIndex: 'type',
      render: (data) => {
        return data === 'singleSelect' ? '单选' : '多选';
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            const values = record?.attributeValues?.map((item) => item.value);
            setCurrentRow({ ...record, values });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          title="确认删除吗"
          key="delete"
          onConfirm={async () => {
            await deleteProductAttribute(record.id);
            init();
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const init = async () => {
    const resp = await getProductAttributeList({
      page: 1,
      pageSize: 50,
    });

    const { list } = resp?.data;
    setDataSource(list);
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="key"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        dataSource={dataSource}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
        onLoad={init}
        options={false}
      />
      <ModalForm
        title={'新建'}
        width="400px"
        modalProps={{
          destroyOnClose: true,
        }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.RuleListItem);
          if (success) {
            handleModalOpen(false);
            init();
          }
        }}
      >
        <ProFormText
          label="名称"
          rules={[
            {
              required: true,
            },
          ]}
          name="name"
        />
        {/* <ProFormSelect
          mode="tags"
          rules={[
            {
              required: true,
            },
          ]}
          label="SKU项"
          name="values"
        /> */}
        <Form.Item
          label="SKU项"
          name="attributeValues"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <FormControlRender>
            {(itemProps) => {
              return <DynamicInput {...pickControlPropsWithId(itemProps)} />;
            }}
          </FormControlRender>
        </Form.Item>

        <ProFormSelect
          options={[
            { label: '单选', value: 'singleSelect' },
            { label: '多选', value: 'multiSelect' },
          ]}
          rules={[
            {
              required: true,
            },
          ]}
          label="选择类型"
          name="type"
        />
      </ModalForm>

      <ModalForm
        title={'编辑'}
        modalProps={{
          destroyOnClose: true,
        }}
        width="400px"
        open={updateModalOpen}
        onOpenChange={(vis) => {
          handleUpdateModalOpen(vis);
          if (!vis) setCurrentRow(undefined);
        }}
        onFinish={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            init();
          }
        }}
        initialValues={currentRow}
      >
        <ProFormText
          label="名称"
          rules={[
            {
              required: true,
            },
          ]}
          name="name"
        />
        <Form.Item
          label="SKU项"
          name="attributeValues"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <FormControlRender>
            {(itemProps) => {
              return <DynamicInput {...pickControlPropsWithId(itemProps)} />;
            }}
          </FormControlRender>
        </Form.Item>
        <ProFormSelect
          options={[
            { label: '单选', value: 'singleSelect' },
            { label: '多选', value: 'multiSelect' },
          ]}
          rules={[
            {
              required: true,
            },
          ]}
          label="选择类型"
          name="type"
        />
        <ProFormDigit label="id" name="id" hidden />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
